package com.sub.kafka.demo;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName KafkaConsumerDemo
 * @Description: Kafka消费者案例
 * @Author Submerge.
 * @Since 2025/6/1 00:16
 * @Version 1.0
 */
public class KafkaConsumerDemo {

    public static void main(String[] args) {

        //配置消费者
        Map<String, Object> config = new HashMap<>();
        config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        config.put(ConsumerConfig.GROUP_ID_CONFIG, "sub-group");

        //创建KafkaConsumer对象
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(config);

        //订阅主题
        kafkaConsumer.subscribe(Collections.singletonList("sub-topic"));

        //消费者拉取消息
        while (true) {
            //每隔100毫秒，抓取一次数据
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record);
            }
        }

        //关闭资源
        //kafkaConsumer.close();


    }
}
